package de.baumann.browser.api.net.base;

import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import de.baumann.browser.utils.MD5Util;

public class MapBuilder {

    private static SortedMap<String, Object> innerMap;
    static String mSaltStr = "06fb7dcb9d4248c5b3bfa5cea9d2000";

    public static MapBuilder create() {
        innerMap = new TreeMap<>();
        return new MapBuilder();
    }

    public MapBuilder add(String key, Object value) {
        innerMap.put(key, value);
        return this;
    }

    public MapBuilder addAll(Map map) {
        if (innerMap == null) {
            innerMap = new TreeMap<>();
        }
        innerMap.putAll(map);
        return this;
    }

    public SortedMap map() {
        String joinString = joinSign(innerMap);
        innerMap.put("sign", joinString);
        return innerMap;
    }

    public String joinSign(SortedMap<String, Object> map) {
        StringBuilder buffer = new StringBuilder();
        Set set = map.entrySet();
        for (Object aSet : set) {
            Map.Entry entry = (Map.Entry) aSet;
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            buffer.append(k).append("=").append(v).append("&");
        }
        if (buffer.length() > 0) {
            buffer.deleteCharAt(buffer.length() - 1);
        }
        buffer.append(mSaltStr);
        return MD5Util.md5encode(buffer.toString(), "UTF-8");
    }

}
